package com.tedu.firstspringboot.controller;

import com.tedu.firstspringboot.entity.Article;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

@Controller
public class ArticleController {
    private static File writeDir;
    static {
        writeDir = new File("writes");
        if (!writeDir.exists()){
           writeDir.mkdirs();
        }
    }
    @RequestMapping("/writeArticle")
    public void publish(HttpServletRequest request, HttpServletResponse response){
        System.out.println("发表文章！！！！！！！！！！！！！！");
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");

        if (title==null||title.isEmpty()||
                author==null||author.isEmpty()||
                content==null||content.isEmpty()){
            try {
                response.sendRedirect("/article_fail.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        Article article = new Article(title,author,content);
        File file = new File(writeDir,title+".obj");
        try(
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                ){
            oos.writeObject(article);
            response.sendRedirect("/article_success.html");
            return;
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
